using Godot;
using GodotThirdGame.addons.MyJoyStick.scripts;

namespace GodotThirdGame.Scripts;

public partial class Player : Area2D
{
    [Signal]
    public delegate void HitEventHandler();

    [Export] public AnimatedSprite2D Anims;
    [Export] public CollisionShape2D Coll;
    
    [Export] public VirtualJoystick JoystickInput;

    [Export] public int Speed { get; set; } = 400;
    [Export] public Vector2 ScreenSize { get; set; }

    public override void _Ready()
    {
        Anims = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
        Coll = GetNode<CollisionShape2D>("CollisionShape2D");

        ScreenSize = GetViewportRect().Size;
        GD.Print($"ScreenSize: {ScreenSize}");

        Hide();
    }

    public override void _Process(double delta)
    {
        // 同时支持键盘和虚拟摇杆
        var velocity = Vector2.Zero;

        // 键盘输入
        var keyboardInput = Vector2.Zero;
        if (Input.IsActionPressed("MoveRight"))
            keyboardInput.X += 1;
        if (Input.IsActionPressed("MoveLeft"))
            keyboardInput.X -= 1;
        if (Input.IsActionPressed("MoveDown"))
            keyboardInput.Y += 1;
        if (Input.IsActionPressed("MoveUp"))
            keyboardInput.Y -= 1;

        // 虚拟摇杆输入（使用原始的非标准化向量）
        Vector2 joystickInput = JoystickInput.Dir;
        joystickInput *= 0.5f;

        // 优先使用摇杆输入，如果没有摇杆输入则使用键盘
        if (joystickInput != Vector2.Zero)
            velocity = joystickInput;
        else
            velocity = keyboardInput.Normalized();

        if (velocity.Length() > 0)
        {
            Anims.Animation = "Walk";
            Anims.FlipH = velocity.X < 0;
            Anims.Play();
        }
        else
        {
            Anims.Animation = "Idle";
            Anims.Stop();
        }

        velocity = velocity * Speed;
        Position += velocity * (float)delta;
        Position = new Vector2(
            Mathf.Clamp(Position.X, 0, ScreenSize.X),
            Mathf.Clamp(Position.Y, 0, ScreenSize.Y));
    }

    private void OnBodyEntered(Node2D body)
    {
        Hide(); // Player disappears after being hit.
        EmitSignal(SignalName.Hit);
        // Must be deferred as we can't change physics properties on a physics callback.
        Coll.SetDeferred("disabled", true);
    }

    public void Start(Vector2 position)
    {
        Position = position;
        Show();
        Coll.Disabled = false;
    }
}